import React , { useReducer , createContext, useContext } from 'react'

const AppContext = createContext();

export const useAppContext = () => useContext(AppContext);

const appState = {
    list:[],
    color:"red"
}

export const ADD_TODOLIST_ITEM = "add-todolist-item";
export const DELETE_TODOLIST_ITEM = "delete-todolist-item";
export const TOGGLE_TODOLIST_ITEM = "toggle-todolist-item";

const AppReducer = (state,action) => {
    switch (action.type) {
        case ADD_TODOLIST_ITEM:
            return {...state,list:[{
                id:Date.now(),
                title:action.title,
                done:false
            },...state.list]}
        case DELETE_TODOLIST_ITEM:
            return {...state,
                list:state.list.filter(item => action.id !== item.id)
            }
        case TOGGLE_TODOLIST_ITEM:
            return {...state,list:state.list.map(item => {
                    return item.id === action.id?{...item,done:!item.done}:item;
                })
            }
        default:
            return state;
    }
}

const AppProvider = ({children}) => {
    const [state,dispatch] = useReducer(AppReducer,appState);

  return <AppContext.Provider
    value={{state,dispatch}}
  >
    {children}
  </AppContext.Provider>
}

export default AppProvider;